/**
 * Address 业务逻辑实现类
 * @author yanwl
 * @date 2015-03-12
 */
package com.chnbst.bstyun.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.chnbst.bstyun.core.base.BaseService;
import com.chnbst.bstyun.core.common.helper.DaoHelper;
import com.chnbst.bstyun.model.pojo.Address;
import com.chnbst.bstyun.model.vo.AddressVo;
import com.chnbst.bstyun.service.AddressService;

@Transactional
@Service
public class AddressServiceImpl extends BaseService implements AddressService {
	
	//声明命名空间
	private final static String nameSpace = "com.chnbst.bstyun.mapper.AddressMapper";
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@Override
	public boolean deleteAddress(Integer addressId) {
		return DaoHelper.delete(nameSpace, "deleteAddress", addressId);
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@Override
	public boolean insertAddress(Address address) {
		return DaoHelper.insert(nameSpace, "insertAddress", address);
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@Override
	public boolean updateAddress(Address address) {
		return DaoHelper.update(nameSpace, "updateAddress", address);
	}
	
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@Override
	public Address selectAddress(Integer addressId) {
		return (Address)DaoHelper.query(nameSpace, "selectAddress", addressId);
	}

	@SuppressWarnings("unchecked")
	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@Override
	public List<AddressVo> selectAddressVos(Integer userId) {
		return (List<AddressVo>)DaoHelper.list(nameSpace, "selectAddressVos", userId);
	}

	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@Override
	public int selectAddressRows(Integer userId) {
		return DaoHelper.count(nameSpace, "selectAddressRows", userId);
	}

	@Transactional(propagation=Propagation.REQUIRED,readOnly=true)
	@Override
	public AddressVo selectAddressVoByMap(Map<String, Object> map) {
		return (AddressVo)DaoHelper.query(nameSpace, "selectAddressVoByMap", map);
	}

	@Transactional(propagation=Propagation.REQUIRED,readOnly=false)
	@Override
	public boolean setDefalutAddress(Integer userId,Integer addressId) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("userId", userId);
		map.put("isDefault", 1);
		AddressVo aVo = selectAddressVoByMap(map);
		if(aVo != null) {
			//用户之前有默认地址
			aVo.setIsDefault(0);
			updateAddress(aVo);
		}
		
		Address address = selectAddress(addressId);
		address.setIsDefault(1);
		boolean isSuccess = updateAddress(address);
		return isSuccess;
	}
}
